package com.smt.modules.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.smt.common.base.BaseController;
import com.smt.common.enums.Code;
import com.smt.common.utils.*;
import com.smt.modules.bus.entity.EmailStreamEntity;
import com.smt.modules.bus.entity.StreamEntity;
import com.smt.modules.bus.service.EmailStreamService;
import com.smt.modules.bus.service.StreamService;
import com.smt.modules.bus.vo.StreamVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 短信流水
 *
 * @author murong
 * @email 981620741@qq.com
 * @date 2018-10-08 14:43:49
 */
@RestController
@RequestMapping("app/stream")
@Api(tags = {"AppStreamController"},description = "短信流水(客户端使用)")
@Slf4j
public class AppStreamController extends BaseController{
    @Autowired
    private EmailUtil emailUtil;
    @Autowired
    private StreamService streamService;
    @Autowired
    private EmailStreamService emailStreamService;


    private static String smsCode = "SMS_128465243";

    private static String signName = "易树智造";
    /**
     * 发送短信验证码
     */
    @ApiOperation(value = "/获取发送短信验证码",notes = "获取发送短信验证码",response = StreamVo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobileNumber",value = "手机号",required = true,dataType = "String",paramType = "query")
    })
    @PostMapping("/getVerifyCode")
    public R getVerifyCode(@NotBlank(message = "必填参数不能为空")String mobileNumber) {
        //生成验证码
        String verifyCode = StringUtil.getFourRandom();
        //判断是否是邮箱
        boolean email = CheckUtil.checkEmail(mobileNumber);
        if(email){
            //存数据库
            int count = emailStreamService.selectCount(new EntityWrapper<EmailStreamEntity>()
                    .eq("emails", email)
                    .between("create_time", TimeUtil.getCurrentBeginDate(), TimeUtil.getCurrentEndDate()));
            if(count >=10){
                return R.error(EnumToKeyUtil.toInt(Code.UNKNOWN_ERROR),"您今天发送的次数超出");
            }
            emailUtil.sendSimpleMail(mobileNumber,"尊敬的用户，易树智造","您的验证码："+verifyCode);
            EmailStreamEntity emailStreamEntity = new EmailStreamEntity(mobileNumber,null,1,DateTime.now().toDate(),verifyCode);
            boolean insert = emailStreamService.insert(emailStreamEntity);
            return insert?R.ok().put("status",0):R.ok().put("status",55);
        }else{
            Map<String,String> map = new HashMap<>();
            map.put("code",verifyCode);
            String param = JSONObject.toJSONString(map);
            log.info("执行阿里云短信服务前线程:{}",Thread.currentThread().getId());
            Map<String,String> result = streamService.getVerifyCode(signName,smsCode,null,param,mobileNumber);
            log.info("获取短信验证码返回结果:{}",R.ok(result));
            Map<String,Object> mapSatus = new HashMap<>();
            if(map.size() == 0){
                mapSatus.put("status",0);
                return R.ok(mapSatus);
            }else{
                mapSatus.put("status",55);
                return R.ok(mapSatus);
            }
        }
    }
    /**
    * 查询短信流水分页方法
    * @param params
    * @return
    */
    @PostMapping("/list")
    @ApiOperation(value = "/list",notes = "根据条件查询",response = StreamVo.class)
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = streamService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation(value = "/info/{id}",notes = "根据表ID查询",response = StreamVo.class)
    public R info(@PathVariable("id") Long id){
			StreamEntity stream = streamService.selectById(id);

        return R.ok().put("stream", stream);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @ApiOperation(value = "/save",notes = "添加信息保存",response = StreamVo.class)
    public R save(@RequestBody StreamEntity stream){
			streamService.insert(stream.copyPropertiesTo(new StreamEntity()));

        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation(value = "/update",notes = "更新信息保存",response = StreamVo.class)
    public R update(@RequestBody StreamEntity stream){
			streamService.updateById(stream.copyPropertiesTo(new StreamEntity()));

        return R.ok();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete")
    @ApiOperation(value = "/delete",notes = "批量删除",response = StreamVo.class)
    public R delete(@RequestBody Long[] ids){
			streamService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }
}
